package com.example.lucene.test;

import com.example.lucene.model.KnowledgeBase;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.*;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author yanggld
 * @Date 2019/5/24-17:06
 * @Description
 */
public class Indexer {

	private IndexWriter indexWriter;

	public Indexer(String indexDirectoryPath) throws IOException{
		//创建储存索引的类，储存在磁盘上
		Directory indexDirectory = FSDirectory.open(FileSystems.getDefault().getPath(indexDirectoryPath));
		//中文分析器
		Analyzer analyzer = new SmartChineseAnalyzer();
		//配置IndexWriter
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		//创建IndexWriter，可以对索引进行写操作，负责创建索引和打开已经存在的索引
		indexWriter = new IndexWriter(indexDirectory, config);
	}

	public void close() throws CorruptIndexException, IOException{
		indexWriter.close();
	}

	private List<Document> getDocument(List<KnowledgeBase> list) throws IOException{
		List<Document> documents = new ArrayList<>();
		for (KnowledgeBase knowledgeBase : list) {
			//创建document
			Document document = new Document();
			//配置document中fieldType的参数
			FieldType fieldType = new FieldType();
			//表示要存储到索引中,因为比较短所以将内容，文件名和绝对路径都存储到索引里了
			fieldType.setStored(true);
			//表示文档、词频和 位置都被索引
			fieldType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
			//向document中添加内容，文件名和绝对路径这三个域，才能创建这三者的索引
			document.add(new Field("content", knowledgeBase.getContent(),fieldType));
//			document.add(new StoredField("content", knowledgeBase.getContent()));
			documents.add(document);
		}
		return documents;
	}

	public void createIndex(List<KnowledgeBase> list) throws IOException{
		List<Document> documents = getDocument(list);
		for (Document document : documents) {
			indexWriter.addDocument(document);
		}
		indexWriter.commit();
	}
}